package com.cuitrip.business.login;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.service.R;
import com.cuitrip.storage.prefrence.UserPreferences;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.util.NetworkUtil;
import com.lab.rx.TextChangeTargetVisibilitySubscriber;
import com.lab.utils.LogHelper;
import com.lab.utils.Utils;
import com.pnikosis.materialishprogress.ProgressWheel;

import butterknife.ButterKnife;
import butterknife.Bind;

public class LoginActivity extends CustomUiFragmentActivity  implements View.OnClickListener, IProxyCallback {
    private static final String TAG = "LoginActivity";


    private ApiProxy mApiProxy = new ApiProxy(this);

    @Bind(R.id.ct_account)
    EditText ctAccount;
    @Bind(R.id.ct_passwd)
    EditText mPassWd;
    @Bind(R.id.ct_account_clear)
    IconTextView ct_account_clear;
    @Bind(R.id.ct_passwd_visible)
    IconTextView ct_passwd_visible;
    @Bind(R.id.find_password)
    TextView btnFindPassword;
    @Bind(R.id.ct_login)
    TextView btnLogin;
    @Bind(R.id.back_press)
    View btnBackPress;
    @Bind(R.id.fail_reason)
    TextView ctReason;
    @Bind(R.id.progress_wheel)
    ProgressWheel progressWheel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.ct_activity_login);
        ButterKnife.bind(this);
        mPassWd.setTypeface(Typeface.DEFAULT);
        ctAccount.setHint(getString(R.string.phone) + "/" + getString(R.string.mail));
        ct_passwd_visible.setOnClickListener(this);
        ct_passwd_visible.setSelected(false);
        ct_account_clear.setOnClickListener(this);
        btnFindPassword.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        btnBackPress.setOnClickListener(this);
        RxTextView
                .textChangeEvents(ctAccount)
                .subscribe(addSubscriber(new TextChangeTargetVisibilitySubscriber().setTarget(ct_account_clear)));
        //读取默认的账号
        ctAccount.setText(UserPreferences.getInstance().getString(UserPreferences.UserKeys.LOGIN_PHONE_NUM, ""));
        ctAccount.setSelection(ctAccount.getText().length());
        mPassWd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                ctReason.setText("");
                if (valid()) {
                    submit();
                }
                return true;
            }
        });
    }

    @Override
    public boolean initCloseTopBar() {
        return true;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        return null;
    }

    private boolean valid() {
        if (TextUtils.isEmpty(ctAccount.getText())) {
            Utils.shakeView(ctAccount);
            return false;
        }
        if (TextUtils.isEmpty(mPassWd.getText())) {
            Utils.shakeView(mPassWd);
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ct_login:
                ctReason.setText("");
                if (valid()) {
                    submit();
                }
                break;
            case R.id.ct_passwd_visible:
                view.setSelected(!view.isSelected());
                if (view.isSelected()) {
                    ct_passwd_visible.setText(R.string.show_pwd_icon);
                    int selectionEnd = mPassWd.getSelectionEnd();
                    mPassWd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mPassWd.setSelection(selectionEnd);
                } else {
                    ct_passwd_visible.setText(R.string.hide_pwd_icon);
                    int selectionEnd = mPassWd.getSelectionEnd();
                    mPassWd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mPassWd.setSelection(selectionEnd);
                }
                break;
            case R.id.find_password:
                LoginProxy.getInstance().gotoFindPassword(LoginActivity.this);
                break;
            case R.id.ct_account_clear:
                ctAccount.setText("");
                break;
            case R.id.back_press:
                finish();
                break;
        }
    }
    private void submit() {
        if (NetworkUtil.getConnectState(this) == NetworkUtil.CONNECT_NONE) {
            ctReason.setText(R.string.feedback_no_internet_1);
            return;
        }
        ctAccount.setEnabled(false);
        mPassWd.setEnabled(false);
        progressWheel.setVisibility(View.VISIBLE);
        btnLogin.setVisibility(View.INVISIBLE);
        btnLogin.setEnabled(false);
        UserBusiness.login(mApiProxy, ctAccount.getText().toString(), mPassWd.getText().toString());
    }
    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response.getApiName().equals(ApiManager.LOGIN)){
            progressWheel.setVisibility(View.INVISIBLE);
            btnLogin.setVisibility(View.VISIBLE);
            btnLogin.setEnabled(true);
            ctAccount.setEnabled(true);
            mPassWd.setEnabled(true);
            if (response.isResponseNormal()) {
                if (response.result instanceof CtUserInfo) {
                    setResult(RESULT_OK);
                    CtUserInfo info = (CtUserInfo) response.result;
                    UserBusiness.updateDeviceToken(mApiProxy, info);
                    /**
                     * 目前登录进入状态默认都是旅行者
                     */
                    info.setType(CtUserInfo.USER_TRAVEL);
                    CtUserInfo oldInfo = LoginInstance.getInstance().getUserInfo();
                    if (oldInfo == null || (oldInfo != null && !oldInfo.isTravel())) {
                        LoginInstance.update(LoginActivity.this, info, true);
                        LogHelper.e("LoginActivity", "jump index");
                        Intent intent = new Intent(LoginActivity.this, IndexActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } else {
                        LoginInstance.update(LoginActivity.this, info, true);
                    }
                    UserPreferences.getInstance().putString(UserPreferences.UserKeys.LOGIN_PHONE_NUM, ctAccount.getText().toString());
                    try {
                        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finish();
                }
            } else {
                if (response != null && !TextUtils.isEmpty(response.msg)) {
                    ctReason.setText(response.msg);
                }
            }
        }else if (ApiManager.UP_DEVICE_TOKEN.equals(response.getApiName())){
            //do nothing here
        }
        return false;
    }

}

